package com.example.shellcollector.Entity;

import android.annotation.SuppressLint;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.Index;
import androidx.room.PrimaryKey;

import com.example.shellcollector.database.InstalledAppUsageDao;
import com.example.shellcollector.util.AppUsageCollectHelper;

import java.security.InvalidParameterException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Entity(
        tableName = "installed_app_usage",
        indices = {
                @Index(value = { "app_package_name" }, unique = true)
        }
)
public class InstalledAppUsage implements Parcelable {

    @Ignore
    public static final String DATE_PATTERN = "yyyy-MM-dd";

    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "app_name")
    private String appName;

    @ColumnInfo(name = "app_package_name")
    private String appPackageName;

    @ColumnInfo(name = "total_running_time")
    private long totalRunningTime;

    @ColumnInfo(name = "first_running_time")
    private long firstRunningTime;

    @ColumnInfo(name = "last_running_time")
    private long lastRunningTime;

    @ColumnInfo(name = "launch_count")
    private int launchCount;

    public InstalledAppUsage() {}

    @Ignore
    public InstalledAppUsage(String appName, String appPackageName) {
        this.appName = appName;
        this.appPackageName = appPackageName;
    }

    protected InstalledAppUsage(Parcel in) {
        id = in.readInt();
        appName = in.readString();
        appPackageName = in.readString();
        totalRunningTime = in.readLong();
        firstRunningTime = in.readLong();
        lastRunningTime = in.readLong();
        launchCount = in.readInt();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(appName);
        dest.writeString(appPackageName);
        dest.writeLong(totalRunningTime);
        dest.writeLong(firstRunningTime);
        dest.writeLong(lastRunningTime);
        dest.writeInt(launchCount);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Creator<InstalledAppUsage> CREATOR = new Creator<InstalledAppUsage>() {
        @Override
        public InstalledAppUsage createFromParcel(Parcel in) {
            return new InstalledAppUsage(in);
        }

        @Override
        public InstalledAppUsage[] newArray(int size) {
            return new InstalledAppUsage[size];
        }
    };

    public Drawable getAppIcon(PackageManager pm) {
        List<ApplicationInfo> installedApps = pm.getInstalledApplications(0);

        Drawable icon = null;
        for (ApplicationInfo installedApp : installedApps) {
            if (getAppPackageName().equals(installedApp.packageName)) {
                icon = installedApp.loadIcon(pm);
                break;
            }
        }
        return icon;
    }

    @SuppressLint("SimpleDateFormat")
    private static String toText(long timestamp) {
        return new SimpleDateFormat(DATE_PATTERN).format(new Date(timestamp));
    }

    public String getAppTotalRunningTimeText() {
        return getTotalRunningTime() / (1000 * 60) + "分钟";
    }

    /**
     * Calculate app usage per day during a series of days.
     * @param startTime begin timestamp of the duration
     * @param endTime end timestamp of the duration
     * @return a list of AppDailyUsage object
     */
    public List<AppDailyUsage> getUsageGroupByDay(InstalledAppUsageDao installedAppUsageDao, long startTime, long endTime) {

        if (startTime > endTime) {
            throw new InvalidParameterException("start time should be smaller than end time");
        }

        List<AppDailyUsage> appDailyUsages;

        long start = AppUsageCollectHelper.getStartTimeOfDayLocal(startTime);
        long end = AppUsageCollectHelper.getStartTimeOfDayLocal(endTime);
        appDailyUsages = installedAppUsageDao.getAppDailyUsagesInRange(
                installedAppUsageDao.getAppUsage(getAppPackageName()).getId(), start, end);
        return appDailyUsages;
    }

    public long getTotalRunningTime() {
        return totalRunningTime;
    }

    public void setTotalRunningTime(long totalRunningTime) {
        this.totalRunningTime = totalRunningTime;
    }

    public String getAppName() {
        return appName;
    }

    public String getAppPackageName() {
        return appPackageName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

    public void setAppPackageName(String appPackageName) {
        this.appPackageName = appPackageName;
    }

    public long getFirstRunningTime() {
        return firstRunningTime;
    }

    public void setFirstRunningTime(long firstRunningTime) {
        this.firstRunningTime = firstRunningTime;
    }

    public long getLastRunningTime() {
        return lastRunningTime;
    }

    public void setLastRunningTime(long lastRunningTime) {
        this.lastRunningTime = lastRunningTime;
    }

    public void setLaunchCount(int launchCount) {
        this.launchCount = launchCount;
    }

    public int getLaunchCount() {
        return launchCount;
    }
}
